package com.spa.application.service.shop;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spa.application.command.massagist.WithdrawAccountCommand;
import com.spa.application.command.shop.ShopWithdrawApplyNewCommand;
import com.spa.application.command.shop.WithdrawAuditCommand;
import com.spa.application.config.massagist.ProfitRule;
import com.spa.application.dto.PageResult;
import com.spa.application.dto.login.LoginUser;
import com.spa.application.dto.massagist.MassagistFinanceDetailDTO;
import com.spa.application.dto.massagist.OrderListWithdrawDTO;
import com.spa.application.dto.massagist.WithdrawAccountDTO;
import com.spa.application.dto.shop.*;
import com.spa.application.query.massagist.MessagistWithdrawRecordDetailQuery;
import com.spa.application.query.shop.*;
import com.spa.domain.entity.MassagistWithdrawRecord;
import com.spa.domain.entity.OrderInfo;
import com.spa.domain.entity.Profit;
import com.spa.domain.entity.Shop;
import com.spa.domain.entity.ShopUser;
import com.spa.domain.entity.ShopWithdrawRecord;
import com.spa.domain.service.*;
import com.spa.infrastructure.enums.dict.UserTypeEnum;
import com.spa.infrastructure.enums.dict.base.WhetherTypeEnum;
import com.spa.infrastructure.enums.dict.order.OrderOperStatusEnum;
import com.spa.infrastructure.enums.dict.order.OrderStatusEnum;
import com.spa.infrastructure.enums.dict.profit.OrderProfitType;
import com.spa.infrastructure.enums.dict.profit.OrderType;
import com.spa.infrastructure.enums.withdraw.WithdrawStatusEnum;
import com.spa.infrastructure.exception.SpaException;
import com.spa.infrastructure.mapper.MassagistWithdrawRecordMapperStruct;
import com.spa.infrastructure.mapper.OrderMapperStruct;
import com.spa.infrastructure.mapper.ShopWithdrawRecordMapperStruct;
import com.spa.infrastructure.mapper.WithdrawAccountMapperStruct;
import com.spa.infrastructure.repository.condition.*;
import com.spa.infrastructure.repository.po.OrderInfoPO;
import com.spa.infrastructure.repository.po.ShopWithdrawRecordPO;
import com.spa.infrastructure.util.DateUtil;
import com.spa.infrastructure.util.RedisUtil;
import com.spa.infrastructure.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@Slf4j
public class ShopWithdrawApplicationService {

    @Autowired
    private ShopWithdrawRecordService shopWithdrawRecordService;

    @Autowired
    private MassagistWithdrawRecordService massagistWithdrawRecordService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private ShopUserService shopUserService;

    @Autowired
    private MassagistService massagistService;

    @Autowired
    private OrderService orderService;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private ProfitService profitService;

    @Resource
    private WithdrawAccountService withdrawAccountService;

    public ShopFinanceDTO finance() {
        ShopFinanceDTO shopFinanceDTO = new ShopFinanceDTO();
        Long shopId = SessionUtil.getUser().getShopId();
        Date date = new Date();
        String beginDate = cn.hutool.core.date.DateUtil.beginOfMonth(date).toString(DatePattern.NORM_DATETIME_FORMAT);
        String endDate = cn.hutool.core.date.DateUtil.endOfMonth(date).toString(DatePattern.NORM_DATETIME_FORMAT);
        ShopIncomeDTO shopIncomeDTO = shopService.getShopIncomeDetailDTO(shopId, beginDate, endDate);
        shopFinanceDTO.setCurrentPerformance(shopIncomeDTO.getCurrentPerformance());
        shopFinanceDTO.setCurrentIncome(shopIncomeDTO.getCurrentIncome());
        shopFinanceDTO.setCashAvailable(getCashAvailable());
        shopFinanceDTO.setWithdrawalDate(withdrawalDate());
        return shopFinanceDTO;
    }

    /**
     * 发起提现
     * @param command
     */
    @Transactional
    public void applyNew(ShopWithdrawApplyNewCommand command) {
        if (command.getAmount() <= 0) {
            throw new SpaException("错误操作！");
        }
        LoginUser loginUser = SessionUtil.getUser();
        long shopId = loginUser.getShopId();
        String lockKey = "shop：withdraw：lock:" + shopId;
        String id = UUID.fastUUID().toString(true);
        try {
            boolean lockFlag = redisUtil.getLock(lockKey, id);
            if (!lockFlag) {
                throw new SpaException("操作频繁！");
            }
            if (getCashAvailable() < command.getAmount()) {
                throw new SpaException("余额不足！");
            }
            ShopUser shopUser = shopUserService.getShopUserById(loginUser.getUserId());
            if (BeanUtil.isNotEmpty(shopUser) && !shopUser.getIsPrincipal().equals(WhetherTypeEnum.$0.getCode())) {
                throw new SpaException("提现功能只对门店负责人开放");
            }
            Shop shop = shopService.getShopById(shopId);
            if (BeanUtil.isEmpty(shop)) {
                throw new SpaException("获取门店信息失败");
            }
            //2024-03-14 add lig  校验是否在提现周期内
            ShopWithdrawRecord shopWithdrawRecord = getLastWithdrawRecord(shopId);
            if (!verifyWithdrawPeriod(shop, shopWithdrawRecord)) {
                throw new SpaException(String.format("老板提现周期%s天(%s天是个变量，根据后台配置的数据显示)还没有到哦！", shop.getWithdrawPeriod(), shop.getWithdrawPeriod()));
            }
            // 查询提现的订单列表
            List<OrderInfo> orderInfoList;
            OrderInfoCondition condition = new OrderInfoCondition();
            condition.setWithdrawShopId(shopId);
            if (command.getApplyType() == 1){
                orderInfoList = orderService.orderList(condition);
            }else{
                condition.setOrderIds(command.getOrderIds());
                orderInfoList = orderService.orderList(condition);
            }
            // 检测是否有已提现的订单，防止重复提现
            if(!checkOrderListIsWithdraw(orderInfoList) || CollectionUtil.isEmpty(orderInfoList)){
                throw new SpaException("提现失败，请稍后再试！");
            }
            // 生成提现记录
            ShopWithdrawRecordPO po = ShopWithdrawRecordMapperStruct.INSTANCE.commandShopWithdrawRecord2Po(command);
            po.setShopId(shopId);
            po.setShopName(shop.getName());
            shopWithdrawRecordService.add(po);
            // 更新门店提现账户表
            WithdrawAccountCommand withdrawAccountCommand = getWithdrawAccountCommand(command, shopId);
            withdrawAccountService.upsertWithdrawAccount(WithdrawAccountMapperStruct.INSTANCE.command2Entity(withdrawAccountCommand));
            // 提现成功之后，更新订单
            if (orderInfoList != null) {
                updateWithdraw(orderInfoList, po.getId());
            }
        } finally {
            redisUtil.releaseLock(lockKey, id);
        }
    }
    /**检测是否有已提现的订单*/
    private boolean checkOrderListIsWithdraw(List<OrderInfo> orderInfoList) {
        if(CollectionUtil.isNotEmpty(orderInfoList)){
            for (OrderInfo orderInfo : orderInfoList) {
                if(orderInfo.getShopWithdrawId() != null){
                    return false;
                }
            }
        }
        return true;
    }
    /** 构造门店提现账户 */
    private static WithdrawAccountCommand getWithdrawAccountCommand(ShopWithdrawApplyNewCommand command, long shopId) {
        WithdrawAccountCommand withdrawAccountCommand =new WithdrawAccountCommand();
        withdrawAccountCommand.setType(UserTypeEnum.$20.getCode());
        withdrawAccountCommand.setMainId(shopId);
        withdrawAccountCommand.setBankName(command.getRealName());
        withdrawAccountCommand.setBankAccount(command.getBankNo());
        withdrawAccountCommand.setBankDetail(command.getBankDetail());
        withdrawAccountCommand.setBankNumber(command.getBankNumber());
        withdrawAccountCommand.setBankPic(command.getBankPic());
        return withdrawAccountCommand;
    }

    /**
     * 获取门店的上一次提现记录
     */
    private ShopWithdrawRecord getLastWithdrawRecord(long shopId) {
        ShopWithdrawRecordCondition condition = new ShopWithdrawRecordCondition();
        condition.setShopId(shopId);
        List<ShopWithdrawRecord> shopWithdrawRecords = shopWithdrawRecordService.list(condition);
        if (shopWithdrawRecords.isEmpty()) {
            return null;
        }
        return shopWithdrawRecords.get(0);
    }

    /**
     * 获取此次提现涉及到的订单（状态是已完成和已出发后取消涉及到车费的）
     * 订单的创建时间是在上一次发起提现时间之后的
     */
    private List<OrderInfo> getApplyWithdrawOrderList(long shopId, String beginDate) {
        OrderInfoCondition condition = new OrderInfoCondition();
        condition.setShopId(shopId);
        condition.setBeginDate(beginDate);
        List<OrderInfo> orderInfos = orderService.orderList(condition);
        List<OrderInfo> complete = orderInfos.stream().filter(orderInfo -> Objects.equals(orderInfo.getStatus(), OrderStatusEnum.$40.getCode())).toList();
        List<OrderInfo> cancel = orderInfos.stream().filter(orderInfo -> Objects.equals(orderInfo.getStatus(), OrderStatusEnum.$99.getCode())
                && (Objects.equals(orderInfo.getOrderOperStatus(), OrderOperStatusEnum.$20.getCode())
                || Objects.equals(orderInfo.getOrderOperStatus(), OrderOperStatusEnum.$30.getCode()))).toList();
        List<OrderInfo> result = new ArrayList<>();
        result.addAll(cancel);
        result.addAll(complete);
        return result;
    }

    private void updateWithdraw(List<OrderInfo> orderInfos, long shopWithdrawId) {
        for (OrderInfo orderInfo : orderInfos) {
            OrderInfoPO po = new OrderInfoPO();
            po.setId(orderInfo.getId());
            po.setShopWithdrawId(shopWithdrawId);
            orderService.updateOrder(po);
        }
    }

    private Integer getCashAvailable() {
        long shopId = SessionUtil.getUser().getShopId();
        //计算门店总收入
        List<Profit> profits = profitService.queryProfitByShopId(shopId, null, null);
        if (CollUtil.isNotEmpty(profits)) {
            // 计算门店已经提现的收入
            ShopWithdrawRecordCondition shopWithdrawRecordCondition = new ShopWithdrawRecordCondition();
            shopWithdrawRecordCondition.setShopId(shopId);
            List<ShopWithdrawRecord> shopWithdrawRecords = shopWithdrawRecordService.list(shopWithdrawRecordCondition);
            int shopSum = shopWithdrawRecords.stream().map(ShopWithdrawRecord::getAmount).reduce(Integer::sum).orElse(0);
            int shopIncome = profits.stream().filter(ObjectUtil::isNotNull).mapToInt(p -> ObjectUtil.isNotNull(p.getShopIncome()) ? p.getShopIncome() : 0).sum();
            return Math.max(shopIncome - shopSum, 0);
        }
        return 0;
    }

    public PageResult<ShopWithdrawListDTO> page(ShopWithdrawQuery query) throws ParseException {
        ShopWithdrawRecordCondition condition = ShopWithdrawRecordMapperStruct.INSTANCE.query2Condition(query);
        condition.setBeginTime(DateUtil.date2Str(DateUtil.getStartTimeOfCurrentMonth(DateUtil.str2Date(query.getApplyTime(), "yyyy-MM"))));
        condition.setEndTime(DateUtil.date2Str(DateUtil.getEndTimeOfCurrentMonth(DateUtil.str2Date(query.getApplyTime(), "yyyy-MM"))));
        condition.setShopId(SessionUtil.getUser().getShopId());
        Page<ShopWithdrawRecord> page = shopWithdrawRecordService.page(condition);
        return ShopWithdrawRecordMapperStruct.INSTANCE.entity2ShopWithdrawListDto4Page(page);
    }

    public PageResult<ShopWithdrawAuditListDTO> auditPage(ShopWithdrawAuditQuery query) {
        MassagistWithdrawRecordCondition condition = MassagistWithdrawRecordMapperStruct.INSTANCE.query2Condition(query);
        condition.setShopId(SessionUtil.getUser().getShopId());
        Page<MassagistWithdrawRecord> page = massagistWithdrawRecordService.page(condition);
        return MassagistWithdrawRecordMapperStruct.INSTANCE.entity2ShopWithdrawAuditListDto4Page(page);
    }

    public ShopWithdrawProgressDTO progress(ShopWithdrawQuery query) {
        return ShopWithdrawRecordMapperStruct.INSTANCE.entity2ShopWithdrawProgressDto(shopWithdrawRecordService.getDetailById(query.getShopWithdrawId()));
    }

    public void audit(WithdrawAuditCommand command) {
        MassagistWithdrawRecord massagistWithdrawRecord = massagistWithdrawRecordService.getDetailById(command.getWithdrawId());
        if (massagistWithdrawRecord.getStatus() != WithdrawStatusEnum.$10.getCode()) {
            throw new SpaException("当前状态不能审核！");
        }
        long shopUserId = SessionUtil.getUser().getExtUserId();
        ShopUser shopUser = shopUserService.getShopUserById(shopUserId);
        String name = shopUser.getPhone();
        massagistWithdrawRecordService.shopAudit(command.getWithdrawId(), shopUserId, name);
    }

    private MassagistFinanceDetailDTO getcurrentPerformance() {
        Long shopId = SessionUtil.getUser().getShopId();
        Date date = new Date();
        String beginDate = cn.hutool.core.date.DateUtil.beginOfMonth(date).toString(DatePattern.NORM_DATETIME_FORMAT);
        String endDate = cn.hutool.core.date.DateUtil.endOfMonth(date).toString(DatePattern.NORM_DATETIME_FORMAT);
        return massagistService.sumServiceIncomeByShop(shopId, beginDate, endDate);
    }

    /**
     * @return boolean true 可以提现，false 不可以提现
     * @description: 验证门店提现周期
     * @author: lig
     * @date: 2024/3/14
     */
    private boolean verifyWithdrawPeriod(Shop shop, ShopWithdrawRecord shopWithdrawRecord) {
        if (BeanUtil.isEmpty(shopWithdrawRecord)) {
            return true;
        }
        Date applyTime = shopWithdrawRecord.getApplyTime();
        Date allowDate = cn.hutool.core.date.DateUtil.offsetDay(applyTime, shop.getWithdrawPeriod());
        //相差天数
        int result = cn.hutool.core.date.DateUtil.compare(allowDate, new Date(), "yyyy-MM-dd");
        if (result == 1) {
            return false;
        }
        return true;

    }

    /**
     * 门店可提现订单分页列表
     * @param query
     * @return
     */
    public PageResult<ShopWithdrawOrderListDTO> orderList(ShopWithdrawOrderListQuery query) {
        long shopId = SessionUtil.getUser().getShopId();
        OrderInfoCondition condition = ShopWithdrawRecordMapperStruct.INSTANCE.query2OrderInfoWithdrawCondition(query);
        condition.setWithdrawShopId(shopId);
        OrderService.OrderInfoPlug plug = OrderService.OrderInfoPlug.empty();
        plug.setProfit(true);
        Page<OrderInfo> orderInfoPage = orderService.pageByCondition(condition, plug);
        // 计算每笔订单的分佣合计
        List<OrderProfitInfo> orderProfitInfoList = calculateOrderProfit(orderInfoPage.getRecords());
        PageResult<ShopWithdrawOrderListDTO> result = OrderMapperStruct.INSTANCE.entity2ShopWithdrawOrderListDTO4Page(orderInfoPage);
        result.getRecords().forEach(orderListWithdrawDTO -> {
            OrderProfitInfo orderProfitInfo = orderProfitInfoList.stream().filter(item -> item.getOrderId().equals(orderListWithdrawDTO.getId())).findFirst().orElse(null);
            if (orderProfitInfo!=null){
                orderListWithdrawDTO.setAmount(orderProfitInfo.getShopIncome());
            }
        });
        return result;
    }

    /**
     * 提现订单详情
     * @param query
     * @return
     */
    public ShopWithdrawOrderDetailDTO orderDetail(ShopWithdrawOrderDetailQuery query) {
        OrderService.OrderInfoPlug plug = OrderService.OrderInfoPlug.empty();
        plug.setOrderExt(true);
        plug.setProfit(true);
        plug.setTicket(true);
        OrderInfo orderInfo = orderService.getOrderInfoById(query.getOrderId(), plug);
        if (ObjectUtil.isNull(orderInfo)){
            throw new SpaException("订单查询失败！");
        }
        if (ObjectUtil.isNotNull(orderInfo) && !orderInfo.getShopId().equals(SessionUtil.getUser().getShopId())){
              throw new SpaException("订单查询失败！");
        }
        ShopWithdrawOrderDetailDTO shopWithdrawOrderDetailDTO = OrderMapperStruct.INSTANCE.entity2ShopWithdrawOrderDetailDTO(orderInfo);
        // 计算每笔订单的分佣合计
        List<OrderProfitInfo> orderProfitInfoList = calculateOrderProfit(Collections.singletonList(orderInfo));
        OrderProfitInfo orderProfitInfo = orderProfitInfoList.stream().filter(item -> item.getOrderId().equals(orderInfo.getId())).findFirst().orElse(null);
        if (orderProfitInfo != null) {
            if (Objects.equals(query.getType(), OrderProfitType.$2.getCode())){
                shopWithdrawOrderDetailDTO.setTotalIncome(orderProfitInfo.getShopIncome());
            }else{
                shopWithdrawOrderDetailDTO.setTotalIncome(orderProfitInfo.getMassagistIncome()+orderProfitInfo.getTravelPrice());
            }
        }
        // 利润数据里面的提成比例拿出来
        List<Profit> profitList = orderInfo.getProfitList();
        // 订单分佣金额和比例
        List<OrderProfitRateInfo> orderProfitRateInfoList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(profitList)){
            profitList.forEach(profit -> {
                String ruleData = profit.getRuleData();
                if (ruleData!=null){
                    ProfitRule profitRule = JSONUtil.toBean(profit.getRuleData(), ProfitRule.class);
                    OrderProfitRateInfo orderProfitRateInfo =  new OrderProfitRateInfo();
                    orderProfitRateInfo.setOrderId(profit.getOrderId());
                    orderProfitRateInfo.setOrderType(profit.getOrderType());
                    if (Objects.equals(query.getType(), OrderProfitType.$2.getCode())){
                        orderProfitRateInfo.setIncome(profit.getShopIncome());
                        orderProfitRateInfo.setRate(Convert.toDouble(profitRule.getShopPercent(), 0D));
                    }else{
                        orderProfitRateInfo.setIncome(profit.getMassagistIncome());
                        orderProfitRateInfo.setRate(Convert.toDouble(profitRule.getMassagistPercent(), 0D));
                    }
                    if (Objects.equals(profit.getOrderType(), OrderType.$1.getCode()) || Objects.equals(profit.getOrderType(), OrderType.$3.getCode())){
                        orderProfitRateInfo.setOrderId(profit.getOrderId());
                    }else if (Objects.equals(profit.getOrderType(), OrderType.$2.getCode()) && profit.getExtendOrderId()!=null){
                        orderProfitRateInfo.setOrderId(profit.getExtendOrderId());
                    }
                    orderProfitRateInfoList.add(orderProfitRateInfo);
                }
            });
        }
        // 订单分佣金额、分佣比例赋值
        OrderProfitRateInfo orderProfitRateInfo = orderProfitRateInfoList.stream().filter(item->item.getOrderId().equals(orderInfo.getId()) && item.getOrderType() ==1).findFirst().orElse(null);
        shopWithdrawOrderDetailDTO.setPercent(orderProfitRateInfo!=null?orderProfitRateInfo.getRate():null);
        shopWithdrawOrderDetailDTO.setIncome(orderProfitRateInfo!=null? (float) orderProfitRateInfo.getIncome() :null);
        // 加钟订单分佣比例赋值
        List<ShopWithdrawOrderDetailDTO.Ext> extList = shopWithdrawOrderDetailDTO.getExtList();
        if (extList!=null){
            extList.forEach(ext -> {
                OrderProfitRateInfo orderProfitRateInfoExt = orderProfitRateInfoList.stream().filter(item->item.getOrderId().equals(ext.getId()) && item.getOrderType() ==2).findFirst().orElse(null);
                if (orderProfitRateInfoExt==null){
                    orderProfitRateInfoExt = orderProfitRateInfoList.stream().filter(item->item.getOrderId().equals(ext.getOrderId()) && item.getOrderType() ==2).findFirst().orElse(null);
                }
                if (orderProfitRateInfoExt!=null){
                    ext.setPercent(orderProfitRateInfoExt.getRate());
                    ext.setIncome((float)orderProfitRateInfoExt.getIncome());
                }
            });
        }
        return shopWithdrawOrderDetailDTO;
    }

    /**
     * 提现记录查看对应订单分页列表
     * @param query
     * @return
     */
    public PageResult<ShopWithdrawOrderListDTO> withdrawOrderList(ShopWithdrawRecordDetailOrderListQuery query) {
        OrderInfoCondition condition = new OrderInfoCondition();
        condition.setShopWithdrawId(query.getShopWithdrawId());
        OrderService.OrderInfoPlug plug = OrderService.OrderInfoPlug.empty();
        plug.setProfit(true);
        Page<OrderInfo> orderInfoPage = orderService.pageByCondition(condition, plug);
        // 计算每笔订单的分佣合计
        List<OrderProfitInfo> orderProfitInfoList = calculateOrderProfit(orderInfoPage.getRecords());
        PageResult<ShopWithdrawOrderListDTO> result = OrderMapperStruct.INSTANCE.entity2ShopWithdrawOrderListDTO4Page(orderInfoPage);
        result.getRecords().forEach(orderListWithdrawDTO -> {
            OrderProfitInfo orderProfitInfo = orderProfitInfoList.stream().filter(item -> item.getOrderId().equals(orderListWithdrawDTO.getId())).findFirst().orElse(null);
            if (orderProfitInfo!=null){
                orderListWithdrawDTO.setAmount(orderProfitInfo.getShopIncome());
            }
        });
        return result;
    }

    /**
     * 门店可提现订单总额
     * @return
     */
    public Integer withdrawOrderTotal() {
        Integer orderTotal = 0;
        long shopId = SessionUtil.getUser().getShopId();
        OrderInfoCondition condition = new OrderInfoCondition();
        condition.setWithdrawShopId(shopId);
        List<OrderInfo> orderInfoList = orderService.orderList(condition);
        // 计算每笔订单的分佣合计
        List<OrderProfitInfo> orderProfitInfoList = calculateOrderProfit(orderInfoList);
        orderTotal = orderProfitInfoList.stream().map(OrderProfitInfo::getShopIncome).reduce(Integer::sum).orElse(0);
        return orderTotal;
    }

    /**
     * 最新门店提现账户
     * @return
     */
    public WithdrawAccountDTO lastWithdrawAccount() {
        WithdrawAccountCondition condition = new WithdrawAccountCondition();
        condition.setMainId(SessionUtil.getUser().getShopId());
        condition.setType(UserTypeEnum.$20.getCode());
        return WithdrawAccountMapperStruct.INSTANCE.entity2DTO(withdrawAccountService.getWithdrawAccountPOLast(condition));
    }

    /**
     * 技师提现订单分页列表
     * @param query
     * @return
     */
    public PageResult<OrderListWithdrawDTO> massagistWithdrawOrderList(ShopWithdrawRecordDetailQuery query) {
        OrderInfoCondition condition = ShopWithdrawRecordMapperStruct.INSTANCE.query2ConditionWithdrawOrderListCondition(query);
        OrderService.OrderInfoPlug plug = OrderService.OrderInfoPlug.empty();
        plug.setProfit(true);
        Page<OrderInfo> orderInfoPage = orderService.pageByCondition(condition, plug);
        // 计算每笔订单的分佣合计
        List<OrderProfitInfo> orderProfitInfoList = calculateOrderProfit(orderInfoPage.getRecords());
        PageResult<OrderListWithdrawDTO> result = OrderMapperStruct.INSTANCE.entity2OrderListWithdrawDto4Page(orderInfoPage);
        result.getRecords().forEach(orderListWithdrawDTO -> {
            OrderProfitInfo orderProfitInfo = orderProfitInfoList.stream().filter(item -> item.getOrderId().equals(orderListWithdrawDTO.getId())).findFirst().orElse(null);
            if (orderProfitInfo!=null){
                orderListWithdrawDTO.setMassagistIncome(orderProfitInfo.getMassagistIncome());
                orderListWithdrawDTO.setTravelPrice(orderProfitInfo.getTravelPrice());
                orderListWithdrawDTO.setAmount(orderListWithdrawDTO.getMassagistIncome()+orderListWithdrawDTO.getTravelPrice());
            }
        });
        return result;
    }

    /**
     * 门店最新可提现日期
     * @return
     */
    public String withdrawalDate() {
        LocalDate nowDate = LocalDate.now();
        String withdrawalDate = nowDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        long shopId = SessionUtil.getUser().getShopId();
        Shop shop = shopService.getShopById(shopId);
        ShopWithdrawRecord shopWithdrawRecord = getLastWithdrawRecord(shopId);
        if (ObjectUtil.isNotNull(shopWithdrawRecord)){
            Date applyTime = shopWithdrawRecord.getApplyTime();
            // 将applyTime转换为LocalDate
            ZonedDateTime zonedDateTime = applyTime.toInstant().atZone(ZoneId.systemDefault());
            LocalDate applyLocalDate = zonedDateTime.toLocalDate();
            // 获取门店提现周期
            Integer withdrawPeriod = shop.getWithdrawPeriod();
            withdrawalDate = applyLocalDate.plusDays(withdrawPeriod).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        return withdrawalDate;
    }

    /**
     * 计算每笔订单的分佣合计
     *
     * @param orderInfos
     * @return
     */
    private List<OrderProfitInfo> calculateOrderProfit(List<OrderInfo> orderInfos) {
        List<OrderProfitInfo> profitInfoList = new ArrayList<>();
        for (OrderInfo orderInfo : orderInfos) {
            int massagistIncome = 0;
            int travelPrice = 0;
            int shopIncome = 0;
            if (orderInfo.getProfitList() != null) {
                massagistIncome = orderInfo.getProfitList().stream()
                        .mapToInt(profit -> profit.getMassagistIncome() != null ? profit.getMassagistIncome() : 0)
                        .sum();

                travelPrice = orderInfo.getProfitList().stream()
                        .mapToInt(profit -> profit.getTravelPrice() != null ? profit.getTravelPrice() : 0)
                        .sum();

                shopIncome = orderInfo.getProfitList().stream()
                        .mapToInt(profit -> profit.getShopIncome() != null ? profit.getShopIncome() : 0)
                        .sum();
            }
            OrderProfitInfo orderProfitInfo = new OrderProfitInfo(orderInfo.getId(), massagistIncome, travelPrice, shopIncome);
            profitInfoList.add(orderProfitInfo);
        }
        return profitInfoList;
    }
}

